﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using CoreEx.Common.Extensions;
using CoreEx.Common.Linq;

namespace CoreEx.Database.Linq
{
    public class RelationalExpressionFinder : ExpressionVisitor
    {

        
        public Expression GetRelationalExpression(MemberExpression memberExpression)
        {
            return Visit(memberExpression);                      
        }

        protected override Expression VisitMemberAccess(MemberExpression memberExpression)
        {
            if (!IsRelational(memberExpression.Member))
                return Visit(memberExpression.Expression);
            
            return base.VisitMemberAccess(memberExpression);
        }
        protected bool IsRelational(MemberInfo memberInfo)
        {
            var type = memberInfo.GetMemberType();
            var elementType = type.GetGenericElementType();
            return !elementType.IsSystemType() || elementType.IsEnumerable();
        }


        protected override Expression VisitParameter(ParameterExpression p)
        {
            return base.VisitParameter(p);
        }

    }


}
